package com.zhang.servlet;

import cn.hutool.core.date.DateUtil;
import com.zhang.pojo.Booking;
import com.zhang.service.BookingService;
import com.zhang.service.impl.BookingServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
@WebServlet(urlPatterns = {"/booking"})
public class BookingServlet extends HttpServlet {
    BookingService bookingService = new BookingServiceImpl();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        String opr = req.getParameter("opr");

        if ("select".equals(opr)) {
            List<Booking> b = bookingService.selectBooking();
            req.getSession().setAttribute("list", b);
            resp.sendRedirect("index.jsp");
        } else if ("insert".equals(opr)) {
            Booking booking = new Booking();
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            String name = req.getParameter("name");
            String cardID = req.getParameter("cardID");
            String date = req.getParameter("date");
            booking.setUserName(name);
            booking.setCardId(cardID);
            booking.setBookingDate(DateUtil.parseDate(date));
            int count = bookingService.insertBooking(booking);
            if (count > 0) {
                resp.getWriter().print("<h1>预约成功<h1>");
                resp.sendRedirect("booking?opr=select");
            } else {
                resp.getWriter().print("<h1>预约失败<h1>");
                resp.sendRedirect("booking?opr=select");
            }

        } else if ("update".equals(opr)) {
            int id = Integer.parseInt(req.getParameter("id"));
            int count = bookingService.updateBooking(id);
            if (count > 0) {
                resp.sendRedirect("booking?opr=select");
            } else {
                resp.sendRedirect("booking?opr=select");
            }
        } else if ("check".equals(opr)) {
            String cardID = req.getParameter("cordId");
            boolean flag = bookingService.count(cardID);
            if (flag) {
                resp.getWriter().print("true");
            } else {
                resp.getWriter().print("flag");
            }

        }
    }
}
